package com.flink.demo.coreconcept07;

import org.apache.commons.io.FileUtils;
import org.apache.flink.api.common.functions.RichMapFunction;
import org.apache.flink.api.java.DataSet;
import org.apache.flink.api.java.ExecutionEnvironment;
import org.apache.flink.api.java.operators.DataSource;
import org.apache.flink.configuration.Configuration;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

/**
 * description
 *
 * @author zsyoung@qq.com
 * 2020/7/14 1:10
 */
public class DistributedDemo {
    public static void main(String[] args) throws Exception {
        final ExecutionEnvironment env = ExecutionEnvironment.getExecutionEnvironment();
//        env.registerCachedFile("/Users/wangzhiwu/WorkSpace/quickstart/distributedcache.txt", "distributedCache");
        env.registerCachedFile("D:\\test-data\\flinkCache.txt", "distributedCache");
        //1.注册一个文件，可以使用hdfs上的文件 也可以是本地文件进行测试
        DataSource<String> data = env.fromElements("Linea", "Lineb", "linec", "Lined");


        DataSet<String> result = data.map(new RichMapFunction<String, String>() {
            private ArrayList<String> dataList = new ArrayList<>();

            @Override
            public String map(String value) throws Exception {
                //在这里就可以使用dataList
                System.out.println("使用dataList:" + dataList + "-------" + value);
                //业务逻辑
                return dataList + ": " + value;
            }

            @Override
            public void open(Configuration parameters) throws Exception {
                super.open(parameters);
                //2.使用该缓存文件
                File myFile = getRuntimeContext().getDistributedCache().getFile("distributedCache");
                List<String> lines = FileUtils.readLines(myFile);
                for (String line : lines) {
                    this.dataList.add(line);
                    System.out.println("分布式缓存为：" + line);
                }
            }
        });

        result.print();
    }
}
